package hc.um.action;

import hc.um.Employee;
import hc.um.service.UserService;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class QueryUserInfoServlet
 */
@WebServlet("/QueryUserInfoServlet")
public class QueryUserInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private UserService userService = new UserService();
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public QueryUserInfoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("query userid=" + request.getParameter("userid"));
		this.getUserInfo(request, response);		
	}

	public void getUserInfo(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Employee employee = null;
		if ((employee = userService.getEmployeeById(request.getParameter("userid"))) != null) {
			// response.sendRedirect("./user/officermain.html");
			response.getWriter().write(creatXmlTextQueryUserInfo("Success", employee));
		} else {
			response.getWriter().write(creatXmlTextQueryUserInfo("Fail", employee));
		}
	}
	
	public String creatXmlTextQueryUserInfo(String result, Employee wemployee) {
		String xmltext = "";

		xmltext = "<userquery><result>" + result + "</result>" ;
		
		if( result == "Success" )
		{	
			xmltext += "<firstname>" + wemployee.getFirstName() + "</firstname><lastname>" + wemployee.getLastName() 
				+ "</lastname><roleid>"+wemployee.getRoleID()+"</roleid><rolename>"
				+ wemployee.getRole().getName() + "</rolename><sex>" + wemployee.getSex()
				+ "</sex><birthday>" + wemployee.getBirthday() +"</birthday><phone>"
				+ wemployee.getPhone()+ "</phone><email>" + wemployee.getEmail() 
				+ "</email><address>" + wemployee.getAddress() + "</address><hosptialid>"
				+ wemployee.getHospitalid() + "</hosptialid></userquery>";
		}
		else
		{
			xmltext += "<errormesg>Query user information failed.</errormesg></userquery>";
		}
		
		System.out.println("xmltext="+xmltext);
		
		return xmltext;
	}	
}
